// app
#include "robot_def.h"
#include "robot_cmd.h"
// module
#include "remote_control.h"
#include "ins_task.h"
#include "ch_imu.h"
#include "master_process.h"
#include "message_center.h"
#include "general_def.h"
#include "dji_motor.h"
#include "buzzer.h"

// bsp
#include "bsp_dwt.h"
#include "bsp_log.h"

#include "stdbool.h"

// 私有宏,自动将编码器转换成角度值
#define YAW_ALIGN_ANGLE (YAW_CHASSIS_ALIGN_ECD * ECD_ANGLE_COEF_DJI) // 对齐时的角度,0-360
#define PTICH_HORIZON_ANGLE (PITCH_HORIZON_ECD * ECD_ANGLE_COEF_DJI) // pitch水平时电机的角度,0-360

/* cmd应用包含的模块实例指针和交互信息存储*/
#ifdef GIMBAL_BOARD // 对双板的兼容,条件编译
#include "can_comm.h"
static CANCommInstance *cmd_can_comm; // 双板通信
#endif
#ifdef ONE_BOARD
static Publisher_t *chassis_cmd_pub;   // 底盘控制消息发布者
static Subscriber_t *chassis_feed_sub; // 底盘反馈信息订阅者
#endif                                 // ONE_BOARD

static Chassis_Ctrl_Cmd_s chassis_cmd_send;      // 发送给底盘应用的信息,包括控制信息和UI绘制相关
static Chassis_Upload_Data_s chassis_fetch_data; // 从底盘应用接收的反馈信息信息,底盘功率枪口热量与底盘运动状态等

static RC_ctrl_t *rc_data;              // 遥控器数据,初始化时返回
static Vision_Recv_s *vision_recv_data; // 视觉接收数据指针,初始化时返回
static Vision_Send_s vision_send_data;  // 视觉发送数据

static Publisher_t *gimbal_cmd_pub;            // 云台控制消息发布者
static Subscriber_t *gimbal_feed_sub;          // 云台反馈信息订阅者
static Gimbal_Ctrl_Cmd_s gimbal_cmd_send;      // 传递给云台的控制信息
static Gimbal_Upload_Data_s gimbal_fetch_data; // 从云台获取的反馈信息

static Publisher_t *shoot_cmd_pub;           // 发射控制消息发布者
static Subscriber_t *shoot_feed_sub;         // 发射反馈信息订阅者
static Shoot_Ctrl_Cmd_s shoot_cmd_send;      // 传递给发射的控制信息
static Shoot_Upload_Data_s shoot_fetch_data; // 从发射获取的反馈信息

static Robot_Status_e robot_state; // 机器人整体工作状态
static Work_Mode_e vision_work_mode;
static uint8_t EmergencyHandlerflag = 0;
static gimbal_control_e Gimbal_control;
static float Gimbal[2];

static float yaw_aim_aps = 0.25f;
static float pitch_aim_aps = 0.02f;
static uint16_t dwt = 0;
static uint16_t gimbal_select_flag = 0;
static float current_time = 0;
static float last_time = 0;
static float scan_mode_end_time = 0;
static float last_gimbal_select;

static bool gimbal_online = false;         // 云台是否在线
static bool chassis_motor_enabled = false; // 底盘是否允许运动
static float gimbal_power_on_time = 0.0f;  // 记录云台上电时间
static float last_yaw_current = 0.0f; // 记录上一次云台电机电流
static float last_time_update = 0.0f; // 记录上一次电流发生变化的时间

static int last_HP = 0;                  // 上一次的血量
static float last_hit_time = 0.0f;       // 上一次被击打的时间
static bool auto_spin_active = false;    // 自动小陀螺是否激活
static const float AUTO_SPIN_TIMEOUT = 5000.0f;  // 自动小陀螺超时时间(ms)
static chassis_mode_e previous_mode = CHASSIS_FOLLOW_GIMBAL_YAW;   // 保存之前的底盘模式


#define PITCH_MAX 18.0f
#define PITCH_MIN -4.0f
#define PITCH_MIN2 -18.5F

#define YAW_MAX_ANGLE 290.0f
#define YAW_MIN_ANGLE -110.0f 

void RobotCMDInit()
{
    // Gimbal[0]=0;
    // Gimbal[1]=0;//初始化gimbal调参数组，以便Ozone寻地址
    rc_data = RemoteControlInit(&huart3);   // 修改为对应串口,注意如果是自研板dbus协议串口需选用添加了反相器的那个
    vision_recv_data = VisionInit(NULL); // 视觉通信初始化,如果使用usb则不需要传入参数
    // CH_IMU_Init(&huart1);           // IMU串口初始化，记得波特率改成921600

    gimbal_cmd_pub = PubRegister("gimbal_cmd", sizeof(Gimbal_Ctrl_Cmd_s));
    gimbal_feed_sub = SubRegister("gimbal_feed", sizeof(Gimbal_Upload_Data_s));
    shoot_cmd_pub = PubRegister("shoot_cmd", sizeof(Shoot_Ctrl_Cmd_s));
    shoot_feed_sub = SubRegister("shoot_feed", sizeof(Shoot_Upload_Data_s));

#ifdef ONE_BOARD // 双板兼容
    chassis_cmd_pub = PubRegister("chassis_cmd", sizeof(Chassis_Ctrl_Cmd_s));
    chassis_feed_sub = SubRegister("chassis_feed", sizeof(Chassis_Upload_Data_s));
#endif // ONE_BOARD
#ifdef GIMBAL_BOARD
    CANComm_Init_Config_s comm_conf = {
        .can_config = {
            .can_handle = &hcan1,
            .tx_id = 0x312,
            .rx_id = 0x311,
        },
        .recv_data_len = sizeof(Chassis_Upload_Data_s),
        .send_data_len = sizeof(Chassis_Ctrl_Cmd_s),
    };
    cmd_can_comm = CANCommInit(&comm_conf);
#endif // GIMBAL_BOARD
    chassis_cmd_send.rotate_control = 1.0f; // 旋转控制量,默认1.0
    shoot_cmd_send.attack_mode = NORMAL;
    gimbal_cmd_send.pitch = 0;
    gimbal_cmd_send.yaw = 0;
    gimbal_cmd_send.gimbal_mode = GIMBAL_ZERO_FORCE;
    robot_state = ROBOT_READY; // 启动时机器人进入工作模式,后续加入所有应用初始化完成之后再进入
}

/**
 * @brief 根据gimbal app传回的当前电机角度计算和零位的误差
 *        单圈绝对角度的范围是0~360,说明文档中有图示
 *
 */
static void CalcOffsetAngle()
{
    // 别名angle提高可读性,不然太长了不好看,虽然基本不会动这个函数
    static float angle;
    angle = gimbal_fetch_data.yaw_angle; // 从云台获取的当前yaw电机单圈角度
    // if(flag==0)
    // {
    // angle = gimbal_fetch_data.yaw_motor_single_round_angle; // 从云台获取的当前yaw电机单圈角度
#if YAW_ECD_GREATER_THAN_4096                               // 如果大于180度
    if (angle > YAW_ALIGN_ANGLE)
        chassis_cmd_send.offset_angle = angle - YAW_ALIGN_ANGLE;
    else if (angle <= YAW_ALIGN_ANGLE && angle >= YAW_ALIGN_ANGLE - 180.0f)
        chassis_cmd_send. = angle - YAW_ALIGN_ANGLE;
    else
        chassis_cmd_send.offset_angle = angle - YAW_ALIGN_ANGLE + 360.0f;
#else // 小于180度
    if (angle > YAW_ALIGN_ANGLE && angle <= 180.0f + YAW_ALIGN_ANGLE)
        chassis_cmd_send.offset_angle = angle - YAW_ALIGN_ANGLE;
    else if (angle > 180.0f + YAW_ALIGN_ANGLE)
        chassis_cmd_send.offset_angle = angle - YAW_ALIGN_ANGLE - 360.0f;
    else
        chassis_cmd_send.offset_angle = angle - YAW_ALIGN_ANGLE;
#endif
    // }
    // else
    // {
    //     float vision_yaw_deg = vision_recv_data->yaw; 
    //     float offset_temp = vision_yaw_deg - angle;
    
    //     // 将 offset_temp 归一化到 [-180, 180] 范围
    //     if (offset_temp > 180.0f)
    //     {
    //         offset_temp -= 360.0f;
    //     }
    //     else if (offset_temp < -180.0f)
    //     {
    //         offset_temp += 360.0f;
    //     }
    
    //     chassis_cmd_send.offset_angle = offset_temp;
    // }
}

/**
 * @brief 控制输入为遥控器(调试时)的模式和控制量设置
 *
 */
static void RemoteControlSet()
{
    // chassis_cmd_send.rotate_control = 1.0;
    // 云台软件限位
    // if (gimbal_cmd_send.pitch > PITCH_MAX)
    //     gimbal_cmd_send.pitch = PITCH_MAX;
    // else if (gimbal_cmd_send.pitch < PITCH_MIN)
    //     gimbal_cmd_send.pitch = PITCH_MIN;

    // 左侧开关状态为[中],右侧开关状态为[下],视觉
    if (switch_is_mid(rc_data[TEMP].rc.switch_left)&& switch_is_down(rc_data[TEMP].rc.switch_right))
    {

        //gimbal_cmd_send.yaw = (vision_recv_data->yaw == 0 ? gimbal_cmd_send.yaw : -(vision_recv_data->yaw)); // 由于视觉调试时角度给反所以添加负号-H
        //gimbal_cmd_send.pitch = (vision_recv_data->pitch == 0 ? gimbal_cmd_send.pitch : vision_recv_data->pitch);
        // 待添加,视觉会发来和目标的误差,同样将其转化为total angle的增量进行控制
        //chassis_cmd_send.chassis_mode = CHASSIS_RE_ROTATE;                    // 由于24赛季检录需要滑环检测故调整，调试视觉时请取消注释
        // if(chassis_fetch_data.game_progress == 4)
        // {chassis_cmd_send.chassis_mode = CHASSIS_ROTATE;}
        // else
        // {chassis_cmd_send.chassis_mode = CHASSIS_NO_FOLLOW;}
        if (vision_recv_data->vel_x < 1000 && vision_recv_data->vel_y < 1000 && vision_recv_data->angle < 1000)
        {
            chassis_cmd_send.vy = vision_recv_data->vel_x * 1000 / RADIUS_WHEEL / PI2 * 360.0f * REDUCTION_RATIO_WHEEL;
            chassis_cmd_send.vx = - (vision_recv_data->vel_y * 1000 / RADIUS_WHEEL / PI2 * 360.0f * REDUCTION_RATIO_WHEEL);
            //gimbal_cmd_send.yaw = 0;//vision_recv_data->angle * RAD_2_DEGREE
            // yaw_flag = 1;
        }
        // 首先检查是否为导航模式
        if (vision_recv_data->gimbal_select == 25)  // 导航模式
        {
            // 导航模式下的设置
            gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;
            gimbal_cmd_send.aim_mode = AIM_OFF;     // 不瞄准
            shoot_cmd_send.shoot_mode = SHOOT_OFF;  // 不射击
            shoot_cmd_send.load_mode = LOAD_STOP;   // 不拨弹
            shoot_cmd_send.friction_mode = FRICTION_OFF; // 关闭摩擦轮
            
            // 底盘跟随云台
            chassis_cmd_send.chassis_mode = CHASSIS_FOLLOW_GIMBAL_YAW;
            
            gimbal_cmd_send.yaw = -1 * vision_recv_data->yaw;
            gimbal_cmd_send.pitch = vision_recv_data->pitch;
            // 导航模式下，不执行后续的目标检测和瞄准/射击逻辑
            return;  // 直接返回，跳过后面的目标检测和自动扫描等逻辑
        }
        gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;
        chassis_cmd_send.chassis_mode = CHASSIS_FOLLOW_GIMBAL_YAW; // 跟随云台yaw角度

        // chassis_cmd_send.vx = 80.0f * (float)rc_data[TEMP].rc.rocker_r_; // _水平方向
        // chassis_cmd_send.vy = 80.0f * (float)rc_data[TEMP].rc.rocker_r1; // 1竖直方向
        // chassis_cmd_send.fly_flag = 1;
        // ...

        // if((float)rc_data[TEMP].rc.rocker_r_>400.0f)
        // {
        //     gimbal_select_flag = 100;
        // }
        // 优先判断主相机是否识别到目标
        if (vision_recv_data->target_state == READY_TO_FIRE ||
            vision_recv_data->target_state == TARGET_CONVERGING)
        {
            // 主相机检测到目标，优先采用主相机信息
            dwt = 0;
            gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;  // 主相机控制模式
            gimbal_cmd_send.aim_mode = AIM_ON;
            // 根据不同状态设定拨弹模式
            if (vision_recv_data->target_state == READY_TO_FIRE)
            {
                shoot_cmd_send.load_mode = LOAD_BURSTFIRE;
            }
            else // TARGET_CONVERGING
            {
                shoot_cmd_send.load_mode = LOAD_STOP;
            }
            shoot_cmd_send.shoot_mode = SHOOT_ON;
            shoot_cmd_send.friction_mode = FRICTION_ON;
            yaw_aim_aps = 0.0f;
        }
        else if (vision_recv_data->target_state == NO_TARGET)
        {
            // 主相机未检测到目标
            dwt++;
            // 此处设定默认主相机控制模式，aim_mode关闭
            gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;
            gimbal_cmd_send.aim_mode = AIM_OFF;
            shoot_cmd_send.shoot_mode = SHOOT_ON;
            shoot_cmd_send.load_mode = LOAD_STOP;
            shoot_cmd_send.friction_mode = FRICTION_ON;
            // 如果长时间未检测到目标，则切换到扫描模式
            if(dwt > 2)
            {
                gimbal_cmd_send.gimbal_mode = GIMBAL_AIM_MODE;
            }

            if (vision_recv_data->gimbal_select == 50) 
            {
                // last_time = DWT_GetTimeline_ms();
            // }
            // last_gimbal_select = vision_recv_data->gimbal_select;
            // 如果在持续扫描时间内，则保持高速扫描状态
            // if (DWT_GetTimeline_ms() - last_time < 250) {
                // gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE_AIM;
                gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;
                gimbal_cmd_send.aim_mode = AIM_FAST;
            }
            
        }
        // if (vision_recv_data->target_state == READY_TO_FIRE)
        // {
        //     dwt = 0;
        //     gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;
        //     gimbal_cmd_send.aim_mode = AIM_ON;
        //     shoot_cmd_send.load_mode = LOAD_BURSTFIRE;
        //     shoot_cmd_send.shoot_mode = SHOOT_ON;
        //     shoot_cmd_send.friction_mode = FRICTION_ON;
        //     yaw_aim_aps=0.0f;
        // }
        // if (vision_recv_data->target_state == TARGET_CONVERGING)
        // {
        //     dwt = 0;
        //     gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;
        //     gimbal_cmd_send.aim_mode = AIM_ON;
        //     shoot_cmd_send.load_mode = LOAD_STOP;
        //     shoot_cmd_send.shoot_mode = SHOOT_ON;
        //     shoot_cmd_send.friction_mode = FRICTION_ON;
        //     yaw_aim_aps=0.0f;
        // }
        // if(vision_recv_data->target_state == NO_TARGET)
        // {
        //     dwt++;
        //     //gimbal_cmd_send.pitch = vision_recv_data->pitch;
        //     //gimbal_cmd_send.yaw = vision_recv_data->yaw;
        //     gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;
        //     gimbal_cmd_send.aim_mode = AIM_OFF;
        //     shoot_cmd_send.shoot_mode = SHOOT_ON;
        //     shoot_cmd_send.load_mode = LOAD_STOP;
        //     shoot_cmd_send.friction_mode = FRICTION_ON;
        //     if(dwt >60)
        //         gimbal_cmd_send.gimbal_mode = GIMBAL_AIM_MODE;
        // }
        
    }
    //左中右中
    if(switch_is_mid(rc_data[TEMP].rc.switch_left) && switch_is_mid(rc_data[TEMP].rc.switch_right))
    {
        chassis_cmd_send.chassis_mode = CHASSIS_NO_FOLLOW;
        gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;
        gimbal_cmd_send.aim_mode = AIM_OFF;
    }
    // 左侧开关状态为[下],或视觉未识别到目标,纯遥控器拨杆控制
    if (switch_is_down(rc_data[TEMP].rc.switch_left) || vision_recv_data->target_state == NO_TARGET)
    {   
        // 按照摇杆的输出大小进行角度增量,增益系数需调整
        // gimbal_cmd_send.yaw += 0.0025f * (float)rc_data[TEMP].rc.rocker_l_;
        // gimbal_cmd_send.pitch += 0.001f * (float)rc_data[TEMP].rc.rocker_l1;
        //gimbal_cmd_send.yaw = 0.01f * (float)rc_data[TEMP].rc.rocker_l_;
        //gimbal_cmd_send.pitch += 0.001f * (float)rc_data[TEMP].rc.rocker_l1;
        // gimbal_cmd_send.yaw = Gimbal[0];
        // gimbal_cmd_send.pitch = Gimbal[1];  
        // Gimbal[]用于gimbal调参（阶跃响应），需要调参时取消注释
    }
    if (switch_is_down(rc_data[TEMP].rc.switch_left) && switch_is_down(rc_data[TEMP].rc.switch_right)) // 右侧开关状态[下],底盘小陀螺
    {
        chassis_cmd_send.chassis_mode = CHASSIS_ROTATE; // CHASSIS_ROTATE
        gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;
    }
    if (switch_is_down(rc_data[TEMP].rc.switch_left) && switch_is_mid(rc_data[TEMP].rc.switch_right)) // 右侧开关状态[中],底盘和云台分离,底盘保持不转动
    {
        chassis_cmd_send.chassis_mode = CHASSIS_FOLLOW_GIMBAL_YAW;
        gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;
    }
    // if(switch_is_down(rc_data[TEMP].rc.switch_left))
    // {
    //     gimbal_cmd_send.yaw = -gimbal_fetch_data.gimbal_imu_data.YawTotalAngle;
    // }
    // 
    if (switch_is_mid(rc_data[TEMP].rc.switch_left) && switch_is_down(rc_data[TEMP].rc.switch_right))
    {
    }else
    {
        // 底盘参数,目前没有加入小陀螺(调试似乎暂时没有必要),系数需要调整
        chassis_cmd_send.vx = 80.0f * (float)rc_data[TEMP].rc.rocker_r_; // _水平方向
        chassis_cmd_send.vy = 80.0f * (float)rc_data[TEMP].rc.rocker_r1; // 1竖直方向
    }
    //视觉开火判断
    //主相机用的
    if(gimbal_cmd_send.gimbal_mode == GIMBAL_AIM_MODE)
    {
        if (gimbal_cmd_send.pitch >= PITCH_MAX)
            pitch_aim_aps = -0.05f;
        if (gimbal_cmd_send.pitch <= PITCH_MIN)
            pitch_aim_aps = 0.05f;
        yaw_aim_aps = 0.25f;
        gimbal_cmd_send.yaw += yaw_aim_aps;
        gimbal_cmd_send.pitch += pitch_aim_aps;
    }else if(gimbal_cmd_send.gimbal_mode == GIMBAL_GYRO_MODE)
    {
        
        if(gimbal_cmd_send.aim_mode == AIM_ON)
        {
            gimbal_cmd_send.yaw = -1 * vision_recv_data->yaw;
            gimbal_cmd_send.pitch = vision_recv_data->pitch;
            if (gimbal_cmd_send.pitch > PITCH_MAX)
            gimbal_cmd_send.pitch = PITCH_MAX;
            else if (gimbal_cmd_send.pitch < PITCH_MIN2)
            gimbal_cmd_send.pitch = PITCH_MIN2;
            // yaw_aim_aps=0.0f;
        }
        else if(gimbal_cmd_send.aim_mode == AIM_OFF){
            gimbal_cmd_send.yaw += 0.0025f * (float)rc_data[TEMP].rc.rocker_l_;
            gimbal_cmd_send.pitch += 0.001f * (float)rc_data[TEMP].rc.rocker_l1;
            if (gimbal_cmd_send.pitch > PITCH_MAX)
                gimbal_cmd_send.pitch = PITCH_MAX;
            else if (gimbal_cmd_send.pitch < PITCH_MIN2)
                gimbal_cmd_send.pitch = PITCH_MIN2;
        }
        else if (gimbal_cmd_send.aim_mode == AIM_FAST )
        {
        if (gimbal_cmd_send.pitch >= PITCH_MAX)
            pitch_aim_aps = -0.05f;
        else if (gimbal_cmd_send.pitch <= PITCH_MIN)
            pitch_aim_aps = 0.05f;
        yaw_aim_aps = 1.0f;

        gimbal_cmd_send.yaw += yaw_aim_aps;
        gimbal_cmd_send.pitch += pitch_aim_aps;
        }
        else
        {
            gimbal_cmd_send.pitch = gimbal_fetch_data.gimbal_imu_data.Pitch;
            gimbal_cmd_send.yaw =  -gimbal_fetch_data.gimbal_imu_data.YawTotalAngle;
        }
    }

    // 发射参数

    // 摩擦轮控制,拨轮向上打为负,向下为正
    if (rc_data[TEMP].rc.dial < -100) // 向上超过100,打开摩擦轮
        shoot_cmd_send.friction_mode = FRICTION_ON;
    else
        shoot_cmd_send.friction_mode = FRICTION_OFF;
    // 拨弹控制,遥控器固定为一种拨弹模式,可自行选择
    if (rc_data[TEMP].rc.dial < -500)
    {
        shoot_cmd_send.load_mode = LOAD_BURSTFIRE; // LOAD_BURSTFIRELOAD_1_BULLET
    }
    else
        shoot_cmd_send.load_mode = LOAD_STOP;
    // 射频控制,固定每秒1发,后续可以根据左侧拨轮的值大小切换射频,
    if (rc_data[TEMP].rc.switch_left == 3 && switch_is_down(rc_data[TEMP].rc.switch_right))
    {
        shoot_cmd_send.friction_mode = FRICTION_ON;
        if (vision_recv_data->target_state == READY_TO_FIRE)
            shoot_cmd_send.load_mode = LOAD_BURSTFIRE;
        else
            shoot_cmd_send.load_mode = LOAD_STOP;
    }
    shoot_cmd_send.shoot_rate = 16;
}

// /**
//  * @brief  紧急停止,包括遥控器左上侧拨轮打满/重要模块离线/双板通信失效等
//  *         停止的阈值'300'待修改成合适的值,或改为开关控制.
//  *
//  * @todo   后续修改为遥控器离线则电机停止(关闭遥控器急停),通过给遥控器模块添加daemon实现
//  *
//  */

static void EmergencyHandler()
{
    // 遥控器离线，进入急停模式
    if (!RemoteControlIsOnline() )
    {
        robot_state = ROBOT_STOP;
        gimbal_cmd_send.gimbal_mode = GIMBAL_ZERO_FORCE;
        chassis_cmd_send.chassis_mode = CHASSIS_ZERO_FORCE;
        shoot_cmd_send.shoot_mode = SHOOT_OFF;
        shoot_cmd_send.friction_mode = FRICTION_OFF;
        shoot_cmd_send.load_mode = LOAD_STOP;
        LOGERROR("[CMD] emergency stop!");
    }
    // 拨轮的向下拨超过一半进入急停模式.注意向打时下拨轮是正
    if (rc_data[TEMP].rc.dial > 300 || robot_state == ROBOT_STOP) // 还需添加重要应用和模块离线的判断
    {
        robot_state = ROBOT_STOP;
        gimbal_cmd_send.gimbal_mode = GIMBAL_ZERO_FORCE;
        chassis_cmd_send.chassis_mode = CHASSIS_ZERO_FORCE;
        shoot_cmd_send.shoot_mode = SHOOT_OFF;
        shoot_cmd_send.friction_mode = FRICTION_OFF;
        shoot_cmd_send.load_mode = LOAD_STOP;
        LOGERROR("[CMD] emergency stop!");
    }
    // 遥控器右侧开关为[上],恢复正常运行
    if (switch_is_up(rc_data[TEMP].rc.switch_right))
    {

        EmergencyHandlerflag = 1;
    }
    if (switch_is_mid(rc_data[TEMP].rc.switch_right) && EmergencyHandlerflag == 1)
    {
        robot_state = ROBOT_READY;
        shoot_cmd_send.shoot_mode = SHOOT_ON;

        LOGINFO("[CMD] reinstate, robot ready");
        EmergencyHandlerflag = 0;
        gimbal_cmd_send.yaw = -gimbal_fetch_data.gimbal_imu_data.YawTotalAngle; // 急停时设定值保持与实际值同步，避免恢复时疯转
        gimbal_cmd_send.pitch = 0;
    }
    // 此处为cyx设置，将遥控器急停恢复设置为右上然后右中组合，以防键鼠控制无法急停等
    // 故不建议在右上添加底盘跟随或小陀螺（surprise）
    // else if (switch_is_up(rc_data[TEMP].rc.switch_left)) // 遥控器左侧开关状态为[上],键盘控制
    // {
    //     switch (rc_data[TEMP].key_count[KEY_PRESS_WITH_CTRL][Key_C] % 2) // ctrl+c 进入急停
    //     {
    //     case 0:
    //         robot_state = ROBOT_READY;
    //         shoot_cmd_send.shoot_mode = SHOOT_ON;
    //         gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE;
    //         break;

    //     default:
    //         robot_state = ROBOT_STOP;
    //         gimbal_cmd_send.gimbal_mode = GIMBAL_ZERO_FORCE;
    //         chassis_cmd_send.chassis_mode = CHASSIS_ZERO_FORCE;
    //         shoot_cmd_send.shoot_mode = SHOOT_OFF;
    //         shoot_cmd_send.friction_mode = FRICTION_OFF;
    //         shoot_cmd_send.load_mode = LOAD_STOP;

    //         gimbal_cmd_send.yaw = -gimbal_fetch_data.gimbal_imu_data.YawTotalAngle; // 急停时设定值保持与实际值同步，避免恢复时疯转
    //         gimbal_cmd_send.pitch = 0;
    //         break;
    //     }
    // }
}

static void MouseKeySet()
{
    
}

/**
 * @brief  检测机器人是否受到击打，并自动启动/关闭小陀螺防御
 * @param  current_HP 当前血量
 * @param  robot_state 机器人状态
 * @param  chassis_mode 当前底盘模式的指针
 * @retval None
 */
static void HandleDamageAndAutoSpin(int current_HP, Robot_Status_e robot_state, chassis_mode_e *chassis_mode)
{
    float current_time = DWT_GetTimeline_ms();

    // 判断是否在视觉模式下
    bool is_vision_mode = switch_is_mid(rc_data[TEMP].rc.switch_left) && 
                          switch_is_down(rc_data[TEMP].rc.switch_right);

    // 非视觉模式下，不执行后续自动小陀螺逻辑
    if (!is_vision_mode) {
        return;
    }
    
    // 检查是否为导航模式
    bool is_navigation_mode = (vision_recv_data->gimbal_select == 25);
    if (is_navigation_mode) {
        return; // 导航模式下不执行自动小陀螺防御
    }
    // 0：不旋转，1：顺时针，2：逆时针
    if (vision_recv_data->spin_command > 0) {
        *chassis_mode = CHASSIS_ROTATE;
        
        // 根据视觉指令设置旋转方向
        if (vision_recv_data->spin_command == 1) {
            // 顺时针旋转
            chassis_cmd_send.rotate_control = 1.0f;  // 顺时针
        } else {
            // 逆时针旋转
            chassis_cmd_send.rotate_control = -1.0f;  // 逆时针
        }
        
        // 记录为手动激活，避免自动检测逻辑干扰
        auto_spin_active = true;
        last_hit_time = current_time;  // 更新时间戳
        return;  // 直接返回，不执行后续自动检测逻辑
    }

    // 如果血量下降，说明受到击打
    if (current_HP < last_HP && current_HP > 0) {
        // 记录被击打时间
        last_hit_time = current_time;
        
        // 激活自动小陀螺
        if (!auto_spin_active) {
            auto_spin_active = true;
            previous_mode = *chassis_mode; // 保存当前模式
        }
    }

    // 更新上一次血量记录
    last_HP = current_HP;

    // 检查是否需要关闭自动小陀螺（超过5秒无击打）
    if (auto_spin_active && (current_time - last_hit_time > AUTO_SPIN_TIMEOUT)) {
        auto_spin_active = false;
    }

    // 如果自动小陀螺激活，并且机器人处于正常工作状态，则强制开启小陀螺
    if (auto_spin_active && robot_state == ROBOT_READY) {
        *chassis_mode = CHASSIS_ROTATE;
    } else if (!auto_spin_active && *chassis_mode == CHASSIS_ROTATE) {
        // 判断是否是手动设置的小陀螺模式
        bool manual_spin = (switch_is_down(rc_data[TEMP].rc.switch_left) && 
        switch_is_down(rc_data[TEMP].rc.switch_right));

        // 如果不是手动小陀螺，则恢复之前的模式
        if (!manual_spin) {
        *chassis_mode = previous_mode;
        }
    }
}

/**
 * @brief 判断云台电机是否在线
 * @param last_current 上一次记录的电流值（传入指针以便更新）
 * @param last_time 上一次记录的时间（传入指针以便更新）
 * @param current 电机当前的电流值
 * @return bool 云台电机是否在线（true 表示在线，false 表示离线）
 */
static bool IsGimbalMotorOnline(float *last_current, float *last_time, float current)
{
    float current_time = DWT_GetTimeline_ms(); // 获取当前时间

    // 检测电流是否变化
    if (fabsf(current - *last_current) > 0.1f) // 电流变化超过阈值
    {
        *last_time = current_time; // 更新最后变化时间
        *last_current = current;  // 更新电流值
        return true;              // 电机在线
    }

    // 如果离上一次更新还没超过 500ms，则认为电机在线
    if ((current_time - *last_time) < 500.0f)
    {
        return true;// 电机在线
    }
    else
    {
        return false;// 电机离线
    }
}



/* 机器人核心控制任务,200Hz频率运行(必须高于视觉发送频率) */
void RobotCMDTask()
{
    // chassis_cmd_send.ui_mode = UI_KEEP;
    // 从其他应用获取回传数据
#ifdef ONE_BOARD
    SubGetMessage(chassis_feed_sub, (void *)&chassis_fetch_data);
#endif // ONE_BOARD
#ifdef GIMBAL_BOARD
    chassis_fetch_data = *(Chassis_Upload_Data_s *)CANCommGet(cmd_can_comm);
#endif // GIMBAL_BOARD
    SubGetMessage(shoot_feed_sub, &shoot_fetch_data);
    SubGetMessage(gimbal_feed_sub, &gimbal_fetch_data);

    // 根据gimbal的反馈值计算云台和底盘正方向的夹角,不需要传参,通过static私有变量完成
    CalcOffsetAngle();
    // 根据遥控器左侧开关,确定当前使用的控制模式为遥控器调试还是键鼠
    // if (switch_is_up(rc_data[TEMP].rc.switch_left))
    // {
        // MouseKeySet(); // 调试专用
    // }
    // else
    // {
        RemoteControlSet();
    // } // 遥控器左侧开关状态为[上],键盘控制


    // 设置视觉发送数据,还需增加加速度和角速度数据
    //VisionSetFlag(chassis_fetch_data.self_color, vision_work_mode, 30);//30为弹速
    VisionSetFlag(chassis_fetch_data.self_color, vision_work_mode, 25);//30为弹速
    //顺序为pitch，yaw（需发送总角度，以防出现角度跟随bug），roll
    VisionSetAltitude(gimbal_fetch_data.gimbal_imu_data.YawTotalAngle, gimbal_fetch_data.gimbal_imu_data.Pitch, gimbal_fetch_data.gimbal_imu_data.Roll);

    RefereeSetAltitude(chassis_fetch_data.current_HP, chassis_fetch_data.game_progress);
    // 推送消息,双板通信,视觉通信等
    // 其他应用所需的控制数据在remotecontrolsetmode和mousekeysetmode中完成设置

    shoot_cmd_send.bullet_speed = chassis_fetch_data.bullet_speed;
    // chassis_cmd_send.friction_mode = shoot_cmd_send.friction_mode; 
    chassis_cmd_send.yaw_angle = gimbal_fetch_data.gimbal_imu_data.Yaw;
    chassis_cmd_send.pitch_angle = gimbal_fetch_data.pitch_angle;
    chassis_cmd_send.init_totalangle = shoot_fetch_data.init_totalangle;
    chassis_cmd_send.totalangle = shoot_fetch_data.totalangle;
    // chassis_cmd_send.chassis_power_robot_level = chassis_power_robot_level;
    
    // //视觉小相机用的
    // if(vision_recv_data->gimbal_select == 50)
    // {
    //     gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE_AIM;
    //     if (gimbal_cmd_send.pitch >= PITCH_MAX)
    //         pitch_aim_aps = -0.05f;
    //     if (gimbal_cmd_send.pitch <= PITCH_MIN)
    //         pitch_aim_aps = 0.05f;

    //     yaw_aim_aps = 0.5f;
    //     gimbal_cmd_send.yaw += yaw_aim_aps;
    //     gimbal_cmd_send.pitch += pitch_aim_aps;
    //     // gimbal_select_flag == 0;
    // }

    if(chassis_fetch_data.over_heat_flag==1)
    {
        // shoot_cmd_send.shoot_mode = SHOOT_OFF;
        shoot_cmd_send.load_mode = LOAD_STOP;
        // shoot_cmd_send.friction_mode = FRICTION_OFF;
    }

    bool current_gimbal_online = IsGimbalMotorOnline(
        &last_yaw_current,
        &last_time_update,
        gimbal_fetch_data.yaw_motor_current
    );
    gimbal_cmd_send.motor_online = current_gimbal_online;

    // 3. 云台离线 => 立即急停
    if (!current_gimbal_online)
    {
        gimbal_online = false;
        chassis_motor_enabled = false;

        if (robot_state != ROBOT_STOP)
        {
            // 模拟急停
            // robot_state = ROBOT_STOP;
            gimbal_cmd_send.gimbal_mode = GIMBAL_ZERO_FORCE;
            chassis_cmd_send.chassis_mode = CHASSIS_ZERO_FORCE;
            shoot_cmd_send.shoot_mode = SHOOT_OFF;
            shoot_cmd_send.friction_mode = FRICTION_OFF;
            shoot_cmd_send.load_mode = LOAD_STOP;
        }
        
        //防止上电后疯转，未测试
        gimbal_cmd_send.yaw = -gimbal_fetch_data.gimbal_imu_data.YawTotalAngle;
    }
    // else
    // {
    //     // 4. 离线 => 在线：记录时间，并维持 STOP 状态一段时间
    //     if (!gimbal_online && current_gimbal_online)
    //     {
    //         gimbal_power_on_time = DWT_GetTimeline_ms();
    //         chassis_motor_enabled = false;
    //     }
    //     gimbal_online = current_gimbal_online;

    //     // 5. 等待一段时间（例如 2000ms）后恢复 READY
    //     if (robot_state == ROBOT_STOP && DWT_GetTimeline_ms() - gimbal_power_on_time >= 1000.0f)
    //     {
    //         robot_state = ROBOT_READY;
    //         chassis_motor_enabled = true;
    //     }

    //     // 6. 如果底盘还处于禁用，给个最低优先级的模式免得乱动
    //     if (!chassis_motor_enabled)
    //     {
    //         chassis_cmd_send.chassis_mode = CHASSIS_ZERO_FORCE;
    //     }
    // }

    EmergencyHandler(); // 处理模块离线和遥控器急停等紧急情况


    // 只有在机器人正常状态下才处理击打检测和自动小陀螺
    if (robot_state == ROBOT_READY) {
        HandleDamageAndAutoSpin(
            (int)chassis_fetch_data.current_HP,
            robot_state,
            &chassis_cmd_send.chassis_mode
        );
    }
#ifdef ONE_BOARD
    PubPushMessage(chassis_cmd_pub, (void *)&chassis_cmd_send);
#endif // ONE_BOARD
#ifdef GIMBAL_BOARD
    CANCommSend(cmd_can_comm, (void *)&chassis_cmd_send);
    //chassis_cmd_send.yaw_motor_total_round_angle = gimbal_fetch_data.yaw_motor_total_round_angle;
#endif // GIMBAL_BOARD
    PubPushMessage(shoot_cmd_pub, (void *)&shoot_cmd_send);
    PubPushMessage(gimbal_cmd_pub, (void *)&gimbal_cmd_send);
}
